package com.leinao.core;


import com.leinao.domain.SysDevice;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

/**
 * description
 *
 * @author zhong.wang
 * @date 2025/1/13
 */
public class DevicePool {

    private static final DevicePool INSTANCE = new DevicePool();

    private static final Random RANDOM = new Random();
    private Map<Long, List<Long>> idPool = new ConcurrentHashMap<>();

    private Map<Long, SysDevice> toDevicePool = new ConcurrentHashMap<>();

    private DevicePool() {
        idPool = new ConcurrentHashMap<>(1 << 10);
        toDevicePool = new ConcurrentHashMap<>(1<<10);
    }

    public synchronized void addRelation(Long left,List<Long> right){
        idPool.putIfAbsent(left, right);
    }

    public synchronized void registerToDevice(Long deviceId,SysDevice device){
        toDevicePool.putIfAbsent(deviceId,device);
    }

    public static DevicePool getInstance() {
        return INSTANCE;
    }

    public SysDevice getById(Long deviceId){
        return toDevicePool.get(deviceId);
    }

    public List<Long> getDeviceIds(){
        return new ArrayList<>(toDevicePool.keySet());
    }

    public Long getRandomDeviceId(Long toDeviceId) {
        if (idPool.containsKey(toDeviceId)) {
            List<Long> fromDeviceIds = idPool.get(toDeviceId);
            if (fromDeviceIds != null && !fromDeviceIds.isEmpty()) {
                // 从fromDeviceIds列表中随机选择一个元素
                int randomIndex = RANDOM.nextInt(fromDeviceIds.size());
                return fromDeviceIds.get(randomIndex);
            }
        }
        return null;
    }
}
